﻿using Microsoft.IdentityModel.Tokens;
using SYSoft.Comm;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using SYSoft.Model.ViewModels;

namespace SYSoft.JWT
{
    public class JwtToken
    {
        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="claims"></param>
        /// <returns></returns>
        public static TokenInfoViewModel BuildJwtToken(Claim[] claims)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SystemConfig.secretCredentials));
            var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: SystemConfig.Issurer,
                audience: SystemConfig.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.Add(TimeSpan.FromSeconds(SystemConfig.expires_time)),//接口的过期时间
                signingCredentials: signcreds
            );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //打包返回前台
            return new TokenInfoViewModel
            {
                access_token = encodedJwt,
                expires_in = SystemConfig.expires_time,
                token_type = "Bearer"
            };
        }


        /// <summary>
        /// 解析获取用户Id            登录接口，会把用户信息写入jwt里面，
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static int SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
            }
            catch (Exception e)
            {
                LogHelper.Fatal(e.Message);
                throw;
            }
            return jwtToken.Id.ObjToInt();
        }

    }
}
